//
//  FH_DUApi.m
//  APIManagerProject
//
//  Created by HeTaiQiang on 15/11/17.
//  Copyright © 2017年 HeTaiQiang. All rights reserved.
//

#import "FH_DUApi.h"
#import "AFNetworking.h"

static AFHTTPSessionManager *shareClient;
static FH_DUApi *api;
NSString *const kHttpBaseUrl = @"http://sz.wisdudu.com";

@implementation FH_DUApi


/**
 请求管理单例

 @return 类对象
 */
+ (FH_DUApi *)sharedInstance {
    
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        
        api = [[FH_DUApi alloc] init];
        shareClient = [AFHTTPSessionManager manager];
       
        //设置超时时间
        [shareClient.requestSerializer setTimeoutInterval:15.0f];
        //应该是不需要缓存每次都重新请求
        [shareClient.requestSerializer setCachePolicy:NSURLRequestReloadIgnoringLocalCacheData];
    });
    return api;
}


/**
 *  POST 请求
 *
 *  @param path 请求路径
 *  @param dict 请求参数
 *  @param res  回调结果
 */
- (void)requestPostWithPath:(NSString *)path
                   paramStr:(NSDictionary *)dict
                     result:(void(^)(BOOL success, NSString *msg, id responseObject))res  {
    
    NSString *tmpPath = [NSString stringWithFormat:@"%@%@", kHttpBaseUrl, path];

    // 指定请求文本格式
    shareClient.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/html",@"application/json",@"text/javascript",@"text/json",@"text/plain", nil];
    
    [shareClient POST:tmpPath parameters:dict  progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        if (responseObject) {
            
            NSString *return_msg=[responseObject objectForKey:@"message"];
            NSString *return_num = [responseObject objectForKey:@"errCode"];
            if (return_num.intValue == 1) {
                
                NSDictionary *result=[responseObject objectForKey:@"result"];
                
                res(YES, return_msg, result);
            }
            else
            {
                res(NO, return_msg, nil);
            }
        }
        else {
            res(NO, @"网络错误/其它", nil);
        }
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        res(NO, @"网络错误/其它", nil);
        
    }];

    
}


/**
 *  Get 请求
 *
 *  @param path 请求路径
 *  @param paramDict 请求参数
 *  @param res  回调结果
 */
- (void)requestGetWithPath:(NSString *)path
                 paramDict:(NSDictionary *)paramDict
                    result:(void(^)(BOOL success, NSString *msg, id responseObject))res {
    
    NSString *tmpPath = [NSString stringWithFormat:@"%@%@", kHttpBaseUrl, path];
    
    [shareClient GET:tmpPath parameters:paramDict progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        if (responseObject) {
            
            NSString *return_msg=[responseObject objectForKey:@"message"];
            NSString *return_num = [responseObject objectForKey:@"errCode"];
            
            if (return_num.intValue == 1) {
                
                NSDictionary *result = [responseObject objectForKey:@"result"];
                
                res(YES, return_msg, result);
            }
            else
            {
                res(NO, return_msg, nil);
            }
        }
        else {
            res(NO, @"网络错误/其它", nil);
        }
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        res(NO, @"网络错误/其它", nil);
    }];
    
}


/**
 *  PUT 请求
 *
 *  @param path 请求路径
 *  @param dict 请求参数
 *  @param res  回调结果
 */
-(void)requestPUTWithPath:(NSString *)path
                 paramStr:(NSDictionary *)dict
                   result:(void(^)(BOOL success, NSString *msg, id responseObject))res {
  
    NSString *tmpPath = [NSString stringWithFormat:@"%@%@", kHttpBaseUrl, path];
    
    shareClient.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/html",@"application/json",@"text/javascript",@"text/json",@"text/plain", nil];
    
    [shareClient PUT:tmpPath parameters:dict success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        if (responseObject) {
            
            NSString *return_msg=[responseObject objectForKey:@"message"];
            NSString *return_num = [responseObject objectForKey:@"errCode"];
            if (return_num.intValue == 1) {
                
                NSDictionary *result=[responseObject objectForKey:@"result"];
                
                res(YES, return_msg, result);
            }
            else
            {
                res(NO, return_msg, nil);
            }
        }
        else {
            res(NO, @"网络错误/其它", nil);
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        res(NO, @"网络错误/其它", nil);
    }];
}

/**
 *  Delete 请求
 *
 *  @param path 请求路径
 *  @param dict 请求参数
 *  @param res  回调结果
 */
- (void)requestDeleteWithPath:(NSString *)path
                     paramStr:(NSDictionary *)dict
                       result:(void(^)(BOOL success, NSString *msg, id responseObject))res {
    
    NSString *tmpPath = [NSString stringWithFormat:@"%@%@",kHttpBaseUrl, path];
    
    [shareClient DELETE:tmpPath parameters:dict success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        if (responseObject) {
            
            NSString *return_msg=[responseObject objectForKey:@"message"];
            NSString *return_num = [responseObject objectForKey:@"errCode"];
            if (return_num.intValue == 1) {
                
                NSDictionary *result=[responseObject objectForKey:@"result"];
                
                res(YES, return_msg, result);
            }
            else
            {
                res(NO, return_msg, nil);
            }
        }
        else {
            res(NO, @"网络错误/其它", nil);
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        res(NO, @"网络错误/其它", nil);
    }];
}

/**
 上传单张或多张图片到服务器
 
 @param imageArray 图片数组
 @param res 回调
 */
- (void)uploadImagePlushWithImages:(NSArray<id > *)imageArray
                            result:(void(^)(BOOL success, NSString *msg, NSString *urlStr))res {
    
    AFHTTPSessionManager *manger = shareClient;

    // 设置允许同时最大并发数量，过大容易出问题
    manger.operationQueue.maxConcurrentOperationCount = 9;
    manger.responseSerializer.acceptableContentTypes = [NSSet setWithArray:@[@"application/json",
                                                                             @"text/html",
                                                                             @"text/json",
                                                                             @"text/plain",
                                                                             @"text/javascript",
                                                                             @"text/xml",
                                                                             @"image/*"]];
    
    
    [manger POST:[NSString stringWithFormat:@"%@%@?t=image", kHttpBaseUrl, @"/FileImage.ashx"] parameters:@{@"t" : @"image"} constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        
        for (int i = 0; i < imageArray.count; i++) {
            
            UIImage *image = imageArray[i];
            
            NSData *imageData = UIImageJPEGRepresentation(image, 0.3);
            //NSData *imageData = UIImagePNGRepresentation(image);
            
            NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
            //设置时间格式
            formatter.dateFormat = @"yyyyMMddHHmmss";
            NSString *str = [formatter stringFromDate:[NSDate date]];
            NSString *fileName = [NSString stringWithFormat:@"%@%d.jpg", str,i];
            
            
            [formData appendPartWithFileData:imageData name:[NSString stringWithFormat:@"FileImage"] fileName:fileName mimeType:@"jpg"];
            
        }
        
    } progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        NSString *error = [responseObject valueForKey:@"error"] ;
        NSString *message = [responseObject valueForKey:@"message"] ;
        
        
        if ( error.intValue == 0) {
            
            // 上传成功， 把图片地址分割成数组
            
            // res(YES, message, responseObject);
            
            NSString *url = [responseObject valueForKey:@"url"];
            NSString *name = [responseObject valueForKey:@"filename"];
            NSArray *array = [url componentsSeparatedByString:@","];
            NSArray *fileNameArray = [name componentsSeparatedByString:@","];
            NSMutableString *urlString = [NSMutableString string];
            
            for (int i = 0; i < array.count; i++) {
                
                [urlString appendFormat:@"%@%@/%@,", kHttpBaseUrl, array[i], fileNameArray[i]];
            }
            
            res(YES, message, [urlString substringWithRange:NSMakeRange(0, urlString.length - 1)]);
        }
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        res(NO, @"time out.", nil);
    }];
    
    
}


/**
 *  POST 请求,登录，注册，修改个人资料专用
 *
 *  @param path 请求路径
 *  @param dict 请求参数
 *  @param res  回调结果
 */
- (void)requestCustomPostWithPath:(NSString *)path
                         paramStr:(NSDictionary *)dict
                           result:(void(^)(BOOL success, NSString *msg, id responseObject))res {
    
    NSString *tmpPath = [NSString stringWithFormat:@"%@%@",kHttpBaseUrl, path];
    
    [shareClient POST:tmpPath parameters:dict  progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        if (responseObject) {
            
            NSString *return_msg=[responseObject objectForKey:@"message"];
            NSString *return_num = [responseObject objectForKey:@"errCode"];
            if (return_num.intValue == 1) {
                
                NSDictionary *result=[responseObject objectForKey:@"result"];
                
                res(YES, return_msg, result);
            }
            else
            {
                res(NO, return_msg, nil);
            }
        }
        else {
            
            res(NO, @"网络错误/其它", nil);
        }
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        res(NO, @"网络错误/其它", nil);
        
    }];
    
}

/**
 *  Get 请求,登录，注册，修改个人资料专用
 *
 *  @param path 请求路径
 *  @param paramDict 请求参数
 *  @param res  回调结果
 */
- (void)requestCustomGetWithPath:(NSString *)path
                       paramDict:(NSDictionary *)paramDict
                          result:(void(^)(BOOL success, NSString *msg, id responseObject))res {
    
    NSString *tmpPath = [NSString stringWithFormat:@"%@%@", kHttpBaseUrl, path];
    
    [shareClient GET:tmpPath parameters:paramDict progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        if (responseObject) {
            
            NSString *return_msg=[responseObject objectForKey:@"message"];
            NSString *return_num = [responseObject objectForKey:@"errCode"];
            
            if (return_num.intValue == 1) {
                
                NSDictionary *result = [responseObject objectForKey:@"result"];
                
                res(YES, return_msg, result);
            }
            else
            {
                res(NO, return_msg, nil);
            }
        }
        else {
             res(NO, @"网络错误/其它", nil);
        }
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        res(NO, @"网络错误/其它", nil);
    }];
    
}

@end
